"use client";
import React, { useState } from "react";
import { Copy } from "lucide-react";

function extractText(children: React.ReactNode): string {
    let text = "";
    React.Children.forEach(children, (child: any) => {
        if (typeof child === "string" || typeof child === "number") {
            text += child;
        } else if (
            React.isValidElement<{ children?: React.ReactNode }>(child)
        ) {
            if (child.props.children) {
                text += extractText(child.props.children);
            }
        }
        // 其它类型（如 null、boolean）忽略
    });
    return text;
}

export const MDXComponents = {
    pre: (props: React.ComponentProps<"pre">) => {
        const { children, ...rest } = props;

        // 获取第一个 <code> 子元素
        const codeChild = React.Children.toArray(children).find(
            (c: any) => c.type === "code"
        ) as any;

        // 获取 className 里的 language-xxx
        const className = codeChild?.props?.className || "";
        const match = className.match(/language-(\w+)/);
        const language = match ? match[1] : "txt";

        // 获取原始代码文本
        const raw = extractText(codeChild.props.children);


        const [copied, setCopied] = useState(false);
        const handleCopy = () => {
            try {
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(raw);
                } else {
                    const textarea = document.createElement("textarea");
                    textarea.value = raw;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand("copy");
                    document.body.removeChild(textarea);
                }
                setCopied(true);
                setTimeout(() => setCopied(false), 1500);
            } catch (err) {
                alert("复制失败！");
            }
        };


        return (
            <div className="relative my-4">
                <div className="absolute top-2 right-2 flex items-center space-x-2">
                    {/* 显示语言名 */}
                    <span className="text-xs bg-gray-800 text-white px-2 py-0.5 rounded">
                        {language}
                    </span>
                    {/* 复制按钮 */}
                    <button
                        onClick={handleCopy}
                        className="text-xs bg-white/80 px-2 py-1 rounded hover:bg-white transition"
                    >
                        {copied ? "copied" : <Copy size={14} />}
                    </button>
                </div>
                <pre {...rest}>{children}</pre>
            </div>
        );
    },
};
